package com.game.autoTool.project.web.utils;

import cn.hutool.core.util.ObjectUtil;
import com.game.autoTool.project.web.common.constant.Constant;
import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.YitIdHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lihui
 * @description:
 * @date 2022-06-27
 */
@Component
public class IdGeneratorUtils implements CommandLineRunner {

    private static Logger log = LoggerFactory.getLogger(IdGeneratorUtils.class);

//    @Autowired
//    private RedisCache redisCache;


    @Override
    public void run(String... args) throws Exception {
//        String key = Constant.BJ_PROJECT_REDIS_FOLDER + Constant.REDIS_MAC_ADDRESS;
//        Map<String, Object> cacheMap = redisCache.getCacheMap(key);
//        String macAddress = IpUtils.getHostIp();
        Integer workerId = 1;
//        if (ObjectUtil.isNotEmpty(cacheMap)) {
//            if (ObjectUtil.isNotEmpty(cacheMap.get(macAddress))) {
//                workerId = Integer.parseInt(cacheMap.get(macAddress) + "");
//            } else {
//                for (Map.Entry<String, Object> stringObjectEntry : cacheMap.entrySet()) {
//                    int i = Integer.parseInt(stringObjectEntry.getValue() + "");
//                    if (i > workerId) {
//                        workerId = i;
//                    }
//                }
//                workerId = workerId + 1;
//                Map<String, Object> map = new HashMap<>();
//                map.put(macAddress, workerId);
//                redisCache.setCacheMap(key, map);
//            }
//
//        } else {
//
//            Map<String, Object> map = new HashMap<>();
//            map.put(macAddress, workerId);
//            redisCache.setCacheMap(key, map);
//        }
//
//        log.info("设置的workerId为: {} ", workerId);


        IdGeneratorOptions options = new IdGeneratorOptions(workerId.shortValue());

        //默认值6，支持的 WorkerId 最大值为2^6-1，若 WorkerId 超过64，可设置更大的 WorkerIdBitLength
        int maxWorkerIdNumber = (1 << options.WorkerIdBitLength) - 1;
        if(workerId > maxWorkerIdNumber){
            options.WorkerIdBitLength = (byte)(BigDecimal.valueOf(Math.log(workerId)/Math.log(2)).intValue()+1);
        }

        YitIdHelper.setIdGenerator(options);
    }

}
